const User = require('../models/User');
const Product = require('../models/Product');
const Team = require('../models/Team');
const File = require('../models/File');
const { successResponse, errorResponse } = require('../utils/response');
const logger = require('../utils/logger');

// 获取统计数据
exports.getStats = async (req, res) => {
  try {
    // 统计数据
    const stats = {
      users: {
        total: await User.countDocuments(),
        active: await User.countDocuments({ status: 'active' }),
        inactive: await User.countDocuments({ status: 'inactive' })
      },
      products: {
        total: await Product.countDocuments(),
        active: await Product.countDocuments({ status: 'active' }),
        inactive: await Product.countDocuments({ status: 'inactive' })
      },
      teams: {
        total: await Team.countDocuments(),
        active: await Team.countDocuments({ status: 'active' }),
        inactive: await Team.countDocuments({ status: 'inactive' })
      },
      files: {
        total: await File.countDocuments(),
        byCategory: {}
      }
    };

    // 获取文件类别统计
    const fileCategories = await File.aggregate([
      { $group: { _id: "$category", count: { $sum: 1 } } }
    ]);

    fileCategories.forEach(category => {
      stats.files.byCategory[category._id || 'uncategorized'] = category.count;
    });

    // 系统概览
    const overview = {
      lastRegisteredUsers: await User.find()
        .select('username name createdAt')
        .sort({ createdAt: -1 })
        .limit(5),
      
      lastCreatedProducts: await Product.find()
        .select('name price category createdAt')
        .sort({ createdAt: -1 })
        .limit(5),
      
      lastUploadedFiles: await File.find()
        .select('originalname mimetype size createdAt')
        .sort({ createdAt: -1 })
        .limit(5)
    };

    return successResponse(res, {
      stats,
      overview
    }, '获取统计数据成功');
  } catch (error) {
    logger.error(`获取统计数据失败: ${error.message}`);
    return errorResponse(res, '获取统计数据失败', 500);
  }
};

// 获取图表数据
exports.getCharts = async (req, res) => {
  try {
    // 用户注册趋势 - 按月统计
    const userRegistrationTrend = await User.aggregate([
      {
        $project: {
          year: { $year: "$createdAt" },
          month: { $month: "$createdAt" }
        }
      },
      {
        $group: {
          _id: { year: "$year", month: "$month" },
          count: { $sum: 1 }
        }
      },
      { $sort: { "_id.year": 1, "_id.month": 1 } }
    ]);

    // 转换为前端所需格式
    const userTrend = userRegistrationTrend.map(item => ({
      date: `${item._id.year}-${item._id.month.toString().padStart(2, '0')}`,
      count: item.count
    }));

    // 产品分类分布
    const productCategoryDistribution = await Product.aggregate([
      {
        $group: {
          _id: "$category",
          count: { $sum: 1 }
        }
      },
      { $sort: { count: -1 } }
    ]);

    // 转换为前端所需格式
    const productDistribution = productCategoryDistribution.map(item => ({
      category: item._id || 'uncategorized',
      count: item.count
    }));

    // 团队成员分布
    const teamSizeDistribution = await Team.aggregate([
      {
        $project: {
          name: 1,
          memberCount: { $size: "$members" }
        }
      },
      { $sort: { memberCount: -1 } },
      { $limit: 10 }
    ]);

    // 文件上传趋势 - 按日统计
    const now = new Date();
    const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

    const fileUploadTrend = await File.aggregate([
      {
        $match: {
          createdAt: { $gte: thirtyDaysAgo }
        }
      },
      {
        $project: {
          date: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
        }
      },
      {
        $group: {
          _id: "$date",
          count: { $sum: 1 }
        }
      },
      { $sort: { "_id": 1 } }
    ]);

    return successResponse(res, {
      userTrend,
      productDistribution,
      teamSizeDistribution,
      fileUploadTrend
    }, '获取图表数据成功');
  } catch (error) {
    logger.error(`获取图表数据失败: ${error.message}`);
    return errorResponse(res, '获取图表数据失败', 500);
  }
}; 